<template>
  <div>
    <Icon icon="ant-design:home-outlined" @click="handleToggleSelect" />
    <span class="text-sm" @click="handleToggleSelect">{{ t('当前租户') }}：</span>
    <span v-show="!showSelect" class="text-sm pr-2" @click="handleToggleSelect">
      ({{ currentCorpCode }}) {{ currentCorpName }}
    </span>
    <span v-show="showSelect" class="text-sm pl-2">
      <Select
        showSearch
        :options="corpOptions"
        :value="currentCorpCode"
        @change="handleSwitchCorp"
        style="width: 150px"
      />
    </span>
    <span v-show="showSelect" class="text-sm pr-2" @click="handleToggleSelect">
      <Icon icon="ant-design:close-outlined" />
    </span>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted } from 'vue';
  import Icon from '/@/components/Icon';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Select } from '/@/components/Form';
  import { corpAdminTreeData, switchCorp } from '/@/api/sys/corpAdmin';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    name: 'JeeSiteSwitchCorp',
    components: { Icon, Select },

    setup() {
      const { t } = useI18n();
      const userStore = useUserStore();
      const showSelect = ref<boolean>(false);
      const corpOptions = ref<Recordable[]>([]);
      const currentCorpCode = ref<String>('0');
      const currentCorpName = ref<String>('JeeSite');

      onMounted(async () => {
        currentCorpCode.value = userStore.getPageCacheByKey('currentCorpCode', '0');
        currentCorpName.value = userStore.getPageCacheByKey('currentCorpName', 'JeeSite');
        corpOptions.value = (await corpAdminTreeData({ isShowCode: true })).map((item) => ({
          label: item.name,
          value: item.id,
        }));
      });

      function handleToggleSelect() {
        showSelect.value = !showSelect.value;
      }

      async function handleSwitchCorp(corpCode) {
        await switchCorp(corpCode);
        location.reload();
      }

      return {
        t,
        showSelect,
        corpOptions,
        currentCorpCode,
        currentCorpName,
        corpAdminTreeData,
        handleToggleSelect,
        handleSwitchCorp,
      };
    },
  });
</script>
